<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use DB;
use Overtrue\Pinyin\Pinyin;
use App\Car;

class SearchController extends Controller
{
	//ajax搜索
    public function ajaxSear(Request $request)
    {
    	//声明一个空数组，用来存放匹配的车品牌名
    	$ajaxBrands = [];
    	//如果匹配到的值为拼音
    	if ($request->key == '') {
    		$ajaxBrands = [];
    	} elseif (preg_match("/^[A-Za-z]/", $request->key)) {
    		//从数据表中获取所有品牌
			$brands = DB::table('brand')->select('brand_name')->get();
			//从容器中获取一个品议转化拼音的实例
            $pinyin = app('pinyin');

			foreach($brands as $brand){
	            //将城市名转化为拼音数组
	            $chars = $pinyin->abbr($brand->brand_name);
	            //获取城市首字母的字符
	            $char = substr($chars, 0,1);
	            if (strtolower($request->key) == $char) {
	            	array_push($ajaxBrands, $brand->brand_name);
	            }
			}
		} else {
			$brands = DB::table('brand')
				->where('brand_name', 'like', $request->key.'%')
				->get();
			foreach($brands as $brand){
				array_push($ajaxBrands, $brand->brand_name);
			}
		}
		return $ajaxBrands;
    }



}
